package com.eostoken.eos_wallet.ui.activity;

import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseActivity;
import com.eostoken.eos_wallet.bean.AccountInfo;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.callback.CommonCallback;
import com.eostoken.eos_wallet.mvp.mode.HomeModel;
import com.eostoken.eos_wallet.mvp.presenter.HomePresenterImpl;
import com.eostoken.eos_wallet.mvp.view.HomeView;
import com.eostoken.eos_wallet.utils.ClipboardUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.BUS_DELETE_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.CHANGE_PASSWORD;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_INTERSECTION;
import static com.eostoken.eos_wallet.utils.Constants.EXTRA_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.PERMISSIONS_VIEW;

public class MyWalletInfoActivity extends BaseActivity<HomeModel, HomeView, HomePresenterImpl> implements HomeView {


    @BindView(R.id.groupListView)
    QMUIGroupListView groupListView;
    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;

    private QMUIDialog mQMUIDialog;
    private QMUIDialog mQMUIDialog2;
    private MgpWallet wallet;
    private String inputPassword;
    private String currentAccountName;
    private AccountInfo accountInfo;
    private String accountInfoJson;
    private int type = -1;
    private QMUICommonListItemView walletNameItem;
    private QMUICommonListItemView promptMessageItem;
    private QMUICommonListItemView exportMnemonicsItem;
    private String hint;

    @Override
    protected void initData() {
        wallet = WalletUtils.getCurrentWallet(this);
        currentAccountName = WalletUtils.getCurrentAccountName();
        presenter.requestAccountInfo(Params.getAccountPamars(currentAccountName));
    }

    @Override
    public void initView() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_color_blue));
        BarUtils.setStatusBarLightMode(this, false);
        topbar.setTitle(StringUtils.getString(R.string.str_wallet_management));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (mQMUIDialog == null) {
            mQMUIDialog = DialogHelper.showEditTextDialog(this, getString(R.string.str_password_authentification),
                    getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
        }
        if (mQMUIDialog2 == null) {
            mQMUIDialog2 = DialogHelper.showEditTextDialog(this, getString(R.string.str_input_wallet_name),
                    getString(R.string.str_input_wallet_name), getString(android.R.string.ok), getString(android.R.string.cancel), listener, false);
        }
        initGroupListView();
    }

    @Override
    public int getContentView() {
        return R.layout.activity_wallet_info;
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            EditText editText = ((EditText) view);
            String text = editText.getText().toString().trim();
            Intent intent;
            if (ObjectUtils.equals(text, wallet.getWalletPassword()) && type != 5) {
                switch (type) {
                    case 1://修改密码
                        intent = new Intent(MyWalletInfoActivity.this, BaseWalletActivity.class);
                        intent.putExtra(EXTRA_INTERSECTION, CHANGE_PASSWORD);
                        ActivityUtils.startActivity(intent);
                        break;
                    case 2://导出私钥
                        intent = new Intent(MyWalletInfoActivity.this, ExportPrivateKeyOrMnemonicsActivity.class);
                        intent.putExtra(EXTRA_ACCOUNT_INFO, accountInfoJson);
                        intent.putExtra("isPrivateKey", true);
                        intent.putExtra(EXTRA_WALLET, wallet);
                        ActivityUtils.startActivity(intent);
                        break;
                    case 3://提示信息
                        String hint = wallet.getHint();
                        if (!ObjectUtils.isEmpty(hint)) {
                            QMUIDialog qmuiDialog2 = DialogHelper.showLongMessageDialog(MyWalletInfoActivity.this,
                                    getString(R.string.str_password_prompt_message),
                                    hint, "",
                                    getString(R.string.str_ok), null, new QMUIDialogAction.ActionListener() {
                                        @Override
                                        public void onClick(QMUIDialog dialog, int index) {
                                            dialog.dismiss();
                                        }
                                    });
                            qmuiDialog2.show();
                        } else {
                            ToastUtils.showShort(R.string.str_no_prompt_message);
                        }
                        break;
                    case 4://删除钱包
                        WalletUtils.deleteWallet(MyWalletInfoActivity.this, wallet);
                        WalletUtils.getAllWalletList(MyWalletInfoActivity.this, new CommonCallback() {
                            @Override
                            public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                                List<MgpWallet> allWallets = (List<MgpWallet>) data;
                                boolean isNull = false;
                                if (allWallets == null) {
                                    isNull = true;
                                } else {
                                    if (allWallets.size() <= 0) {
                                        isNull = true;
                                    } else {
                                        isNull = false;
                                    }
                                }
                                if (isNull) {
                                    Intent intent = new Intent(MyWalletInfoActivity.this, AddWalletActivity.class);
                                    ActivityUtils.startActivity(intent);
                                } else {
                                    MgpWallet wallet = allWallets.get(0);
                                    WalletUtils.setCurrentAccountName(wallet.getCurrentAccountName());
                                    WalletUtils.setCurrentPrivatekey(wallet.getPrivateKey());
                                    BusUtils.post(BUS_DELETE_WALLET);
                                }
                                finish();
                            }

                            @Override
                            public void onFailure(String msg, int responseFailCode) {
                                Intent intent = new Intent(MyWalletInfoActivity.this, AddWalletActivity.class);
                                ActivityUtils.startActivity(intent);
                            }
                        });
                        break;
                    case 6://导出助记词
                        intent = new Intent(MyWalletInfoActivity.this, ExportPrivateKeyOrMnemonicsActivity.class);
                        intent.putExtra(EXTRA_ACCOUNT_INFO, accountInfoJson);
                        intent.putExtra("isPrivateKey", false);
                        intent.putExtra(EXTRA_WALLET, wallet);
                        ActivityUtils.startActivity(intent);
                        break;
                }
                type = -1;
            } else {
                if (type == 5) {
                    walletNameItem.setDetailText(ObjectUtils.isEmpty(wallet.getWalletName()) ? getString(R.string.str_wallet_name) : text);
                    wallet.setWalletName(text);
                    WalletUtils.updateWallet(MyWalletInfoActivity.this, wallet);
                } else {
                    ToastUtils.showShort(StringUtils.getString(R.string.str_wrong_password));
                }
            }
            editText.setText("");
            dialog.dismiss();
        }
    };

    private void initGroupListView() {
        QMUICommonListItemView walletAddressItem = groupListView.createItemView(StringUtils.getString(R.string.str_wallet_address));
        walletAddressItem.setOrientation(QMUICommonListItemView.VERTICAL);
        walletAddressItem.setDetailText(wallet.getCurrentAccountName());
        String walletName;
        if (ObjectUtils.isEmpty(wallet)) {
            walletName = getString(R.string.str_mgp_wallet_1);
            hint = "";
        } else {
            hint = wallet.getHint();
            walletName = ObjectUtils.isEmpty(wallet.getWalletName()) ? getString(R.string.str_mgp_wallet_1) : wallet.getWalletName();
        }
        walletNameItem = groupListView.createItemView(
                null,
                getString(R.string.str_wallet_name),
                walletName,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);

        QMUICommonListItemView changePasswordItem = groupListView.createItemView(StringUtils.getString(R.string.str_change_password));
        changePasswordItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        changePasswordItem.setOrientation(QMUICommonListItemView.VERTICAL);

        QMUICommonListItemView resourceManagementItem = groupListView.createItemView(StringUtils.getString(R.string.str_resource_administration));
        resourceManagementItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        resourceManagementItem.setOrientation(QMUICommonListItemView.VERTICAL);

        QMUICommonListItemView exportPrivateKeyItem = groupListView.createItemView(StringUtils.getString(R.string.str_export_privateKey));
        exportPrivateKeyItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        exportPrivateKeyItem.setOrientation(QMUICommonListItemView.VERTICAL);

        exportMnemonicsItem = groupListView.createItemView(StringUtils.getString(R.string.str_export_mnemonics));
        exportMnemonicsItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        exportMnemonicsItem.setOrientation(QMUICommonListItemView.VERTICAL);
        exportMnemonicsItem.setVisibility(ObjectUtils.isEmpty(wallet.getMnemonicCode()) ? View.GONE : View.VISIBLE);

        QMUICommonListItemView permissionsExamineItem = groupListView.createItemView(StringUtils.getString(R.string.str_permissions_view));
        permissionsExamineItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        permissionsExamineItem.setOrientation(QMUICommonListItemView.VERTICAL);

        promptMessageItem = groupListView.createItemView(
                null,
                getString(R.string.str_prompt_message),
                hint,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        promptMessageItem.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        promptMessageItem.setOrientation(QMUICommonListItemView.HORIZONTAL);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment;
                Intent intent;
                if (v instanceof QMUICommonListItemView) {
                    CharSequence text = ((QMUICommonListItemView) v).getText();
                    if (ObjectUtils.equals(StringUtils.getString(R.string.str_wallet_address), text)) {
                        ClipboardUtils.copyText(wallet.getCurrentAccountName());
                        ToastUtils.showShort(StringUtils.getString(R.string.str_copy_success));
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_wallet_name), text)) {
                        type = 5;
                        mQMUIDialog2.show();
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_change_password), text)) {
                        type = 1;
                        mQMUIDialog.show();
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_resource_administration), text)) {
                        intent = new Intent(MyWalletInfoActivity.this, ResourceAdministrationActivity.class);
                        ActivityUtils.startActivity(intent);
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_export_privateKey), text)) {
                        type = 2;
                        mQMUIDialog.show();
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_permissions_view), text)) {
                        intent = new Intent(MyWalletInfoActivity.this, BaseWalletActivity.class);
                        intent.putExtra(EXTRA_INTERSECTION, PERMISSIONS_VIEW);
                        intent.putExtra(EXTRA_ACCOUNT_INFO, accountInfoJson);
                        ActivityUtils.startActivity(intent);
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_prompt_message), text)) {
//                        type = 3;
//                        mQMUIDialog.show();
                    } else if (ObjectUtils.equals(StringUtils.getString(R.string.str_export_mnemonics), text)) {
                        type = 6;
                        mQMUIDialog.show();
                    }
                }
            }
        };

        int size = QMUIDisplayHelper.dp2px(MyWalletInfoActivity.this, 20);
        QMUIGroupListView.newSection(MyWalletInfoActivity.this)
                .setTitle("")
                .setDescription("")
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(walletAddressItem, onClickListener)
                .addItemView(walletNameItem, onClickListener)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(MyWalletInfoActivity.this, 5), 0)
                .addTo(groupListView);

        QMUIGroupListView.newSection(MyWalletInfoActivity.this)
                .setLeftIconSize(QMUIDisplayHelper.dp2px(MyWalletInfoActivity.this, 12), ViewGroup.LayoutParams.WRAP_CONTENT)
                .setTitle("")
                .addItemView(changePasswordItem, onClickListener)
                .addItemView(resourceManagementItem, onClickListener)
                .addItemView(exportPrivateKeyItem, onClickListener)
                .addItemView(exportMnemonicsItem, onClickListener)
                .addItemView(permissionsExamineItem, onClickListener)
                .addItemView(promptMessageItem, onClickListener)
                .addTo(groupListView);
    }

    @OnClick({R.id.deleteWalletBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.deleteWalletBtn:
                type = 4;
                mQMUIDialog.show();
                break;
        }
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case ACCOUNT_INFO:
                accountInfo = (AccountInfo) data;
                accountInfoJson = GsonUtils.toJson(accountInfo);
                break;
        }
    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case ACCOUNT_INFO:
                break;
        }
    }

    @Override
    public HomeModel createModel() {
        return new HomeModel();
    }

    @Override
    public HomeView createView() {
        return this;
    }

    @Override
    public HomePresenterImpl createPresenter() {
        return new HomePresenterImpl(MyWalletInfoActivity.this);
    }

    @Override
    public boolean isShowState() {
        return true;
    }
}
